import request, { requestOld } from '@/utils/request'
import { Message } from 'element-ui'

// 查询工作状态列表
export function listWork(query) {
  return request({
    url: '/data/htrs/list',
    method: 'get',
    params: query
  })
}

export async function batchTask(config) {
  const roomIds = config.rooms.map(i => i.roomId)
  const oldIds = []
  const newIds = []
  config.meterNos.forEach((meterNo, i) => {
    // 设备编号/电表号大于255的是老系统电表，调老接口
    if (Number(meterNo) > 255) {
      oldIds.push(roomIds[i])
    } else {
      newIds.push(roomIds[i])
    }
  })
  const tasks = []
  tasks.push(...newIds.map((roomId, i) => {
    return () => request({
      url: config.newUrl,
      method: 'get',
      params: {
        roomIds: roomId
      }
    }).then(res => {
      return {
        ...config.rooms[i],
        roomId,
        status: res.data.statusList?.[0]?.status + '' || '1'
      }
    })
  }))
  // 旧系统接口，旧系统接口只支持一个一个改，要调用多次接口
  tasks.push(...oldIds.map((roomId, i) => {
    const data = new FormData()
    data.append("RoomId", roomId)
    // 这个回路固定都是1不用改
    data.append("LoopNo", 1)
    return () => requestOld({
      url: config.oldUrl,
      method: 'post',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data
    }).then(res => {
      return {
        ...config.rooms[i],
        status: res.status,
        roomId
      }
    }, err => {
      return {
        ...config.rooms[i],
        status: '1',
        roomId
      }
    })
  }))
  async function nextTask() {
    const task = tasks.shift()
    if (!task) {
      return
    }
    const res = await task()
    config.onItemOver?.(res)
    await nextTask()
  }
  await nextTask()
  // 等所有的接口都处理完再统一返回结果
  // 合并新系统和老系统的接口返回，保持和原来数据格式一样
  if (oldIds.length > 0) {
    await request({
      url: config.updateUrl,
      method: 'get',
      params: {
        roomIds: oldIds.toString()
      }
    }).catch(err => {
      Message.error('同步失败')
    })
  }
}

// 强制开机
export function workBoot(query) {
  return batchTask({
    newUrl: '/data/htrs/boot',
    oldUrl: '/ChaobiaoModule/Tdata_rt_rs/Open',
    meterNos: query.meterNos,
    rooms: query.rooms,
    updateUrl: '/old/refresh/rtRs',
    onItemOver: query.onItemOver
  })
}

/**
 * 召测
 */
export function workCall(query) {
  return batchTask({
    newUrl: '/data/htrs/call',
    oldUrl: '/ChaobiaoModule/Tdata_rt_rs/GetCheckData',
    meterNos: query.meterNos,
    rooms: query.rooms,
    updateUrl: '/old/refresh/rtRs',
    onItemOver: query.onItemOver
  })
}

// 恢复正常
export function workRecover(query) {
  return batchTask({
    newUrl: '/data/htrs/recover',
    oldUrl: '/ChaobiaoModule/Tdata_rt_rs/Recovery',
    meterNos: query.meterNos,
    rooms: query.rooms,
    updateUrl: '/old/refresh/rtRs',
    onItemOver: query.onItemOver
  })
}

// 强制关机
export function shutdownWork(query) {
  return batchTask({
    newUrl: '/data/htrs/shutdown',
    oldUrl: '/ChaobiaoModule/Tdata_rt_rs/Close',
    meterNos: query.meterNos,
    rooms: query.rooms,
    updateUrl: '/old/refresh/rtRs',
    onItemOver: query.onItemOver
  })
}